package es.wtestgen.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final Log log = LogFactory.getLog(HibernateUtil.class);
	
	//private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal threadLocal = new ThreadLocal();
	
	private static final Configuration cfg = new Configuration();
	
	private static org.hibernate.SessionFactory sessionFactory;
	
	public static Session currentSession() throws HibernateException
	{
		log.info("_____Entramos en el m�todo currentSession");
		Session session = (Session) threadLocal.get();
		if (session == null) {
			if (sessionFactory == null) {
				try {
					//cfg.configure(CONFIG_FILE_LOCATION);
					cfg.configure();
					sessionFactory = cfg.buildSessionFactory();
				}catch (Exception e) {
					System.err.println("_______Error Creando SessionFactory_______");
					e.printStackTrace();
				}
			}
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.COMMIT);
			threadLocal.set(session);
		}
		return session;
	}
	public static void closeSession() throws HibernateException {
		log.info("_____Entramos en el m�todo closeSession");
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close();
		}
	}
}